package com.vy.stl.config;

import com.vy.stl.interceptor.AdminInterceptor;
import com.vy.stl.interceptor.MemberInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * @create: 2025/08/21 21:43
 * @description:
 */
@Configuration //标记为配置类，Spring会自动扫描并应用该配置
public class WebConfig implements WebMvcConfigurer {

    @Autowired //自动注入之前定义的AdminInterceptor拦截器
    private AdminInterceptor adminInterceptor;

    @Autowired
    private MemberInterceptor memberInterceptor;

    /**
     * 注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //1. 注册AdminInterceptor拦截器
        registry.addInterceptor(adminInterceptor)
                //2. 设置拦截器作用的路径：/** 表示拦截所有请求
                .addPathPatterns("/**")
                //3. 设置不拦截的路径
                .excludePathPatterns(
                        "/fore/**",
                        "/upload/**",
                        "/captcha",
                        "/login/**",
                        "/admin/login","/admin/getLogin",
                        "/swagger**/**","/**/api/-docs/**",
                        "/error",
                        "/page/**"
//                        ,
//                        "/admin/**",
//                        "/coach/**",
//                        "/course/**",
//                        "/member/**",
//                        "/reserve/**",
//                        "/charts/**"
                );
        registry.addInterceptor(memberInterceptor)
                .addPathPatterns("/fore/**")
                .excludePathPatterns(
                        "/fore/course",
//                        "/fore/member/reg",
                        "/fore/member/login"
                );
    }

    /**
     * 配置CORS过滤器，解决跨域问题
     * @return
     */
    @Bean //将方法返回的对象注册为Spring容器中的Bean
    public CorsFilter corsFilter() {
        //1. 创建基于URL的CORS配置源
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //2. 创建CORS配置对象
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //3. 允许所有来源的请求（生产环境中应指定具体域名）
        corsConfiguration.addAllowedOrigin("*");
        //4. 允许所有请求头
        corsConfiguration.addAllowedHeader("*");
        //5. 允许所有HTTP方法（GET、POST、PUT、DELETE等）
        corsConfiguration.addAllowedMethod("*");
        //6. 为所有路径注册CORS配置
        source.registerCorsConfiguration("/**", corsConfiguration);
        //7. 返回CORS过滤器实例
        return new CorsFilter(source);
    }
}
